package com.ynr.invoice.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.ynr.dao.ICompanyDao;
import com.ynr.dao.IExpenseDao;
import com.ynr.voucher.model.ExpenseModel;
import com.ynr.voucher.service.IVoucherInvoiceService;

@Controller
public class ExpenseController {

	private static final Logger logger = LoggerFactory.getLogger(ExpenseController.class);
	
	@Autowired
	private IExpenseDao expenseDao;
	
	@Autowired
	private IVoucherInvoiceService voucherInvoiceService;
	
	@Autowired
	private ICompanyDao companyDao;
	
	@RequestMapping("/addExpense")
	@ResponseBody
	public Map<String, Object> addExpense(HttpServletRequest request) {
		Map<String, Object> retMap = new HashMap<>();
		try {
			Map<String, String[]> dataMap = request.getParameterMap();
			Map<String, Object> expenseMap = new HashMap<>();
			for(Entry<String, String[]> entry : dataMap.entrySet()) {
				expenseMap.put(entry.getKey(), entry.getValue()[0]);
			}
			long companyId = Long.valueOf((String)expenseMap.get("company_id"));
			expenseMap.remove("company_id");
			if(expenseDao.addExpense(expenseMap) == 1) {
				//写入expense表，并关联在company_expense表
				long expenseId = (long)expenseMap.get("id");
				expenseDao.addCompanyExpense(expenseId, companyId);
				
				//写凭证
				Map<String, Object> companyMap = companyDao.getCompanyById(companyId);
				ExpenseModel expense = JSON.parseObject(JSON.toJSONString(expenseMap), ExpenseModel.class);
				voucherInvoiceService.processExpense(companyMap, expense);
				
				retMap.put("errorCode", "0000");
			} else {
				retMap.put("errorCode", "0001");
			}
		} catch(Exception e) {
			logger.error("addExpense error : {}", e.toString());
			retMap.put("errorCode", "0001");
		}
		return retMap;
	}
	
}
